package anthology.leet_code_hot;

import java.util.function.IntConsumer;

//https://leetcode.cn/problems/print-zero-even-odd/description/
public class _1116打印零与奇偶数 {
    //使用 synchronized 的解法
    class ZeroEvenOdd {
        private int n;
        private volatile int  flag = 1;

        public ZeroEvenOdd(int n) {
            this.n = n;
        }

        // printNumber.accept(x) outputs "x", where x is an integer.
        public void zero(IntConsumer printNumber) throws InterruptedException {
            synchronized (this){
                for(int i=1; i<=n; i++){
                    while (flag % 2 == 0) wait();
                    printNumber.accept(0);
                    flag++;
                    notifyAll();
                }
            }
        }

        public void even(IntConsumer printNumber) throws InterruptedException {
            synchronized (this){
                for(int i=2; i<=n; i+=2){
                    while (flag % 4 != 0) wait();
                    printNumber.accept(i);
                    flag++;
                    notifyAll();
                }
            }
        }

        public void odd(IntConsumer printNumber) throws InterruptedException {
            synchronized (this){
                for(int i=1; i<=n; i+=2){
                    while (flag % 4 != 2) wait();
                    printNumber.accept(i);
                    flag++;
                    notifyAll();
                }
            }
        }
    }
}
